

import serial
import math
from time import sleep
from DataChange import *

import xlrd
import time

import winsound


# import sys
# sys.path.append('E:\_code\python\test1')
# from DataChange import *


COMX_temp='com10'





def COMX(t):
    global COMX_temp
    COMX_temp=t




def bcc(t):
    if(len(t)==0): return 0
    bcc=0
    for i in t:
        bcc^=int(i)
    return bcc


def get(obis='0.0.0',com=COMX_temp,COMX_BAUND1='9600',COMX_BAUND2='9600'):
    s = serial.Serial(com, COMX_BAUND1)
    s.timeout=1
    s.bytesize=8
    s.parity='N'

    dp=print

    def Hand(id,s_port):
        buf = '/?' + id + '!' + '\r\n'
        print('->发送握手接收帧：',buf)
        s_port.write(buf.encode())
        uart_get=(s_port.readall())
        if(len(uart_get)>5):
            print('<-握手接收帧：',uart_get.decode())
            next_baund=uart_get[5]-ord('0')
            print('Meter 支持切换最大波特率',300*math.pow(2,next_baund))
            return True
        elif(len(uart_get)):
            print(uart_get)
        return False

    def ChangeBps(open,bps,s_port):
        if(open==False):
            return True
        print('->pc选择波特率', str(bps), '发送波特率切换帧')
        i = int(math.log(int(bps) / 300, 2))
        buf = '\x06\x30' + str(i) + '\x31\r\n'
        s_port.write(buf.encode())
        sleep(0.1)
        s_port.close()
        print('pc切换波特率到', str(bps))
        s_port.baudrate = str(bps)
        s_port.timeout = 1
        s_port.open()
        uart_get = s_port.readall()
        if uart_get:
            print('<-应答接收(密码)：', uart_get)
            return True
        return False

    def PasswordCheck(password,s_port):
        buf='\x01\x50\x31\x02\x28'+password+'\x29\x03\x61'
        print('->发送(密码)：', buf)
        s_port.write(buf.encode())
        uart_get = s_port.readall()
        if uart_get:
            if uart_get[0]==6 and len(uart_get)==1:
                print('->password ok：', uart_get)
                return True
        return False

    def CloseIec21(s_port):
        print('->发送b0q：')
        buf='\x01\x42\x30\x03\x71'
        s_port.write(buf.encode())
        uart_get = s.readall()
        if uart_get:
            print('->quit：', uart_get)
        s_port.close()

    def ReadObis(obis,s_port,wait=1,timeout=1):
        buf=str2hexs('01 52 31 02 ')+str2bytes(obis.upper())+str2hexs('28 29 03 ')
        # buf = bytes.fromhex('01 52 31 02 ')
        # buf += bytes(obis.upper(), encoding="utf8")
        # buf += bytes.fromhex('28 29 03')
        checknum = bcc(buf[1:])
        buf += bytes((checknum,))
        s_port.timeout = timeout
        s_port.write(buf)
        print('->发送obis：', obis)
        sleep(1)
        a=0
        uart_get =b''
        while(1):
            temp=s_port.readall()
            if len(temp):
                pass
                uart_get+=temp
                print('........get')
                a=0
            else:
                sleep(0.1)
                a+=1
                print('........wait')
            if a>wait:
                break
        if(len(uart_get)):
            return True,uart_get
        else:
            print('err err err err err err err err err err')
            for _ in range(2):
                winsound.Beep(1600, 500)
                sleep(0.5)
            ss = input()
            return False, b''

    CloseIec21(s)
    s.open()
    if Hand('',s)==False:
        CloseIec21(s)
        return False
    if(False==ChangeBps(True,9600,s)):
        CloseIec21(s)
        return False
    if(False==PasswordCheck('00000000',s)):
        CloseIec21(s)
        return False



    book = xlrd.open_workbook("obis.xls")
    sh = book.sheet_by_name('obis')
    o=[]
    for i in range(1,sh.nrows):
        o+=list([sh.cell_value(i, 1)])
    o+=['FF.FF.F3.1','FF.FF.F3.2','FF.FF.F3.3']#,'1.8.0','2.8.0','3.8.0','4.8.0','15.8.0']
    o = [ '1.8.0']

    for _ in range(1):
        for obis in o:
            t=ReadObis(obis,s)
            f = open('log.txt', 'a')
            f.write(time.strftime('%H:%M:%S\n', time.localtime(time.time())))
            f.close()
            with open('log.txt', 'ab') as f:
                f.write(str2bytes("->obis get：%s\n" % (obis)))
            if(t[0]==True):
                print('->data len：', len(t[1]))
                print('->data str：', t[1])
                print('->data hex：', showhexs(t[1]))
                with open('log.txt','ab') as f:
                    f.write(str2bytes("->data len：%s\n" %(len(t[1]))))
                    f.write(str2bytes("->data str：%s\n" % ((t[1]))))
                    f.write(str2bytes("->data hex：%s\n" % (showhexs(t[1]))))

            sleep(1)

    CloseIec21(s)
    for _ in range(2):
        winsound.Beep(1600, 500)
        sleep(0.5)






class Uart(serial.Serial):
    def __init__(self, name, score):
        self.name = name                #定义强制属性
        self.score = score
    def write(self,s):
        print('new send')
        serial.Serial.write(self,s)







s=Uart('com10', '9600')


if __name__ == '__main__':
    pass

    s.timeout=1
    s.bytesize=8
    s.parity='N'
    s.write(b'12345')







